<template>
  <div class="class-management">
    <div class="page-header">
      <div class="header-left">
        <button class="back-btn" @click="goBack">返回主页</button>
        <h2>班级管理</h2>
      </div>
      <button class="add-btn" @click="showAddModal = true">新增班级</button>
    </div>
    
    <div class="class-list">
      <div v-if="loading" class="loading-indicator">加载中...</div>
      <table v-else class="class-table">
        <thead>
          <tr>
            <th>序号</th>
            <th>班级名称</th>
            <th>学生人数</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(cls, index) in classes" :key="cls.id">
            <td>{{ (currentPage - 1) * pageSize + index + 1 }}</td>
            <td>{{ cls.className }}</td>
            <td>{{ cls.student_count || 0 }}</td>
            <td>{{ formatDate(cls.createdAt) }}</td>
            <td>
              <button class="edit-btn" @click="editClass(cls)">编辑</button>
              <button class="delete-btn" @click="deleteClass(cls.id)">删除</button>
              <button class="view-btn" @click="viewStudents(cls.id)">查看学生</button>
            </td>
          </tr>
        </tbody>
      </table>
      <div v-if="classes.length === 0" class="empty-tip">暂无班级数据</div>
      
      <!-- 自定义分页组件 -->
      <div class="pagination">
        <div class="pagination-info">
            共 {{ total }} 条记录，每页
            <select v-model="pageSize" @change="handleSizeChange($event)" class="page-size-select">
              <option v-for="size in pageSizes" :key="size" :value="size">{{ size }}</option>
            </select>
            条
          </div>
        <div class="pagination-controls">
          <button 
            class="page-btn" 
            @click="handlePageChange(currentPage - 1)" 
            :disabled="currentPage === 1"
          >
            上一页
          </button>
          <div class="page-numbers">
            <span 
              v-for="num in visiblePages" 
              :key="num"
              :class="['page-number', { active: currentPage === num }]"
              @click="num !== '...' && handlePageChange(num)"
            >
              {{ num }}
            </span>
          </div>
          <button 
            class="page-btn" 
            @click="handlePageChange(currentPage + 1)" 
            :disabled="currentPage >= totalPages"
          >
            下一页
          </button>
          <div class="page-jumper">
            前往
            <input 
              type="number" 
              v-model.number="currentPage" 
              @keyup.enter="handleJump"
              min="1" 
              :max="totalPages"
              class="page-input"
            >
            页
          </div>
        </div>
      </div>
    </div>
    
    <!-- 新增/编辑班级弹窗 -->
    <div class="modal" v-if="showAddModal || showEditModal" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ isEditMode ? '编辑班级' : '新增班级' }}</h3>
          <button class="close-btn" @click="closeModal">×</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveClass">
            <div class="form-group">
              <label>班级名称 *</label>
              <input type="text" v-model="classForm.name" required placeholder="请输入班级名称">
            </div>
            <div class="modal-footer">
              <button type="submit" class="submit-btn">{{ isEditMode ? '保存' : '创建' }}</button>
              <button type="button" class="cancel-btn" @click="closeModal">取消</button>
            </div>
          </form>
        </div>
      </div>
    </div>
    
    <!-- 查看学生弹窗 -->
    <div class="modal" v-if="showStudentModal" @click="closeStudentModal">
      <div class="modal-content large" @click.stop>
        <div class="modal-header">
          <h3>班级学生 - {{ currentClassName }}</h3>
          <button class="close-btn" @click="closeStudentModal">×</button>
        </div>
        <div class="modal-body">
          <div class="student-list">
            <table class="student-table">
              <thead>
                <tr>
                  <th>学号</th>
                  <th>姓名</th>
                  <th>角色</th>
                  <th>创建时间</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="student in classStudents" :key="student.id">
                  <td>{{ student.username }}</td>
                  <td>{{ student.name }}</td>
                  <td>{{ student.role === 'student' ? '学生' : '教师' }}</td>
                  <td>{{ formatDate(student.createdAt) }}</td>
                  <td>
                    <button class="remove-btn" @click="removeStudent(student.id)">移除</button>
                  </td>
                </tr>
              </tbody>
            </table>
            <div v-if="classStudents.length === 0" class="empty-tip">该班级暂无学生</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { api } from '@/utils/api.js';
import { showMessage, formatDate } from '@/utils/common.js';


export default {
  name: 'ClassManagement',

  data() {
      return {
        classes: [],
        // 分页相关
        currentPage: 1,
        pageSize: 10,
        total: 0,
        pageSizes: [10, 20, 50, 100],
        // 加载状态
        loading: false,
        showAddModal: false,
        showEditModal: false,
        isEditMode: false,
        classForm: {
          id: '',
          name: ''
        },
        showStudentModal: false,
        currentClassId: '',
        currentClassName: '',
        classStudents: []
      };
    },
  computed: {
    totalPages() {
      return Math.ceil(this.total / this.pageSize);
    },
    visiblePages() {
      // 计算可见的页码
      const total = this.totalPages;
      const current = this.currentPage;
      const pages = [];
      
      if (total <= 7) {
        // 如果总页数不超过7页，显示所有页码
        for (let i = 1; i <= total; i++) {
          pages.push(i);
        }
      } else {
        // 如果总页数超过7页，显示当前页附近的页码
        if (current <= 4) {
          // 当前页在前面
          for (let i = 1; i <= 5; i++) {
            pages.push(i);
          }
          pages.push('...', total);
        } else if (current >= total - 3) {
          // 当前页在后面
          pages.push(1, '...');
          for (let i = total - 4; i <= total; i++) {
            pages.push(i);
          }
        } else {
          // 当前页在中间
          pages.push(1, '...');
          for (let i = current - 1; i <= current + 1; i++) {
            pages.push(i);
          }
          pages.push('...', total);
        }
      }
      
      return pages;
    }
  },
  methods: {
    /**
     * 格式化日期
     */
    formatDate(date) {
      return formatDate(date);
    },
    
    /**
     * 加载班级列表（支持分页）
     */
    async loadClasses() {
      this.loading = true;
      try {
        const classData = await api.getClasses({
          page: this.currentPage,
          pageSize: this.pageSize
        });
        
        // 适配后端返回的新数据结构
        if (classData.data && classData.data.classes) {
          this.classes = classData.data.classes;
          this.total = classData.data.total || 0;
        } else {
          // 向后兼容旧数据结构
          this.classes = classData.data || [];
          this.total = this.classes.length;
        }
      } catch (error) {
        showMessage(error.message || '加载班级列表失败', 'error');
      } finally {
        this.loading = false;
      }
    },
    
    /**
     * 页面刷新后重新加载数据
     */
    handleRefresh() {
      this.currentPage = 1;
      this.loadClasses();
    },
    
    /**
     * 处理页码变化
     * @param {number} page - 新页码
     */
    handlePageChange(page) {
      this.currentPage = page;
      this.loadClasses();
    },
    
    /**
     * 处理每页数量变化
     * @param {Event} event - 事件对象
     */
    handleSizeChange(event) {
      // 确保是数字类型
      const newPageSize = parseInt(event.target.value) || 10;
      this.pageSize = newPageSize;
      this.currentPage = 1; // 重置到第一页
      this.loadClasses();
    },
    
    /**
     * 显示编辑班级弹窗
     */
    editClass(cls) {
      this.classForm = {
        id: cls.id,
        name: cls.className
      };
      this.isEditMode = true;
      this.showEditModal = true;
      this.showAddModal = false;
    },
    
    /**
     * 关闭弹窗
     */
    closeModal() {
      this.showAddModal = false;
      this.showEditModal = false;
      this.resetForm();
    },
    
    /**
     * 重置表单
     */
    resetForm() {
      this.classForm = {
        id: '',
        name: ''
      };
      this.isEditMode = false;
    },
    
    /**
     * 保存班级信息
     */
    async saveClass() {
      try {
        if (this.isEditMode) {
          await api.updateClass(this.classForm.id, { name: this.classForm.name });
          showMessage('班级更新成功', 'success');
        } else {
          await api.createClass({ name: this.classForm.name });
          showMessage('班级创建成功', 'success');
        }
        this.closeModal();
        this.loadClasses();
      } catch (error) {
        showMessage(error.message || '操作失败', 'error');
      }
    },
    
    /**
     * 删除班级
     */
    async deleteClass(classId) {
      if (confirm('确定要删除该班级吗？删除后班级相关数据将无法恢复。')) {
        try {
          await api.deleteClass(classId);
          showMessage('班级删除成功', 'success');
          this.loadClasses();
        } catch (error) {
          showMessage(error.message || '删除失败', 'error');
        }
      }
    },
    
    /**
     * 查看班级学生
     */
    async viewStudents(classId) {
      try {
        const cls = this.classes.find(c => c.id === classId);
        this.currentClassId = classId;
        this.currentClassName = cls?.name || '';
        
        const response = await api.getClassStudents(classId);
        // 检查响应结构，获取正确的学生列表数据
        this.classStudents = Array.isArray(response) ? response : (response.data || []);
        this.showStudentModal = true;
      } catch (error) {
        showMessage(error.message || '加载学生列表失败', 'error');
      }
    },
    
    /**
     * 关闭查看学生弹窗
     */
    closeStudentModal() {
      this.showStudentModal = false;
      this.currentClassId = '';
      this.currentClassName = '';
      this.classStudents = [];
    },
    
    /**
     * 移除学生
     */
    async removeStudent(studentId) {
      if (confirm('确定要将该学生从班级中移除吗？')) {
        try {
          await api.removeStudentFromClass(studentId, this.currentClassId);
          showMessage('学生已移除', 'success');
          
          // 重新加载学生列表
          const response = await api.getClassStudents(this.currentClassId);
          // 检查响应结构，获取正确的学生列表数据
          this.classStudents = Array.isArray(response) ? response : (response.data || []);
        } catch (error) {
          showMessage(error.message || '移除失败', 'error');
        }
      }
    },
    
    /**
     * 返回教师主页
     */
    goBack() {
      this.$router.push('/teacher/home');
    },
    
    /**
      * 处理页码跳转
      */
     handleJump() {
       // 确保页码在有效范围内
       this.currentPage = Math.max(1, Math.min(this.currentPage, this.totalPages));
       this.loadClasses();
     }
  },
  mounted() {
    this.loadClasses();
  }
};
</script>

<style scoped>
.class-management {
  padding: 20px;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e8e8e8;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.back-btn {
  padding: 6px 12px;
  background-color: #f0f0f0;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.back-btn:hover {
  background-color: #e0e0e0;
}

.add-btn,
.edit-btn,
.delete-btn,
.view-btn,
.remove-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  margin-left: 5px;
}

.add-btn {
  background-color: #1E9FFF;
  color: white;
}

.add-btn:hover {
  background-color: #40A9FF;
}

.edit-btn {
  background-color: #52c41a;
  color: white;
}

.edit-btn:hover {
  background-color: #73d13d;
}

.delete-btn {
  background-color: #ff4d4f;
  color: white;
}

.delete-btn:hover {
  background-color: #ff7875;
}

.view-btn {
  background-color: #faad14;
  color: white;
}

.view-btn:hover {
  background-color: #ffc53d;
}

.remove-btn {
  background-color: #ff4d4f;
  color: white;
  padding: 4px 8px;
  font-size: 12px;
}

.remove-btn:hover {
  background-color: #ff7875;
}

.class-list,
.student-list {
  flex: 1;
  min-height: 0;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: auto;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    border-top: 1px solid #e8e8e8;
  }
  
  .pagination-info {
    color: #666;
    font-size: 14px;
  }
  
  .page-size-select {
    margin: 0 5px;
    padding: 3px 5px;
    border: 1px solid #ddd;
    border-radius: 4px;
    color: #333;
  }
  
  .pagination-controls {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  
  .page-btn {
    padding: 5px 12px;
    border: 1px solid #ddd;
    background: #fff;
    cursor: pointer;
    border-radius: 4px;
    font-size: 14px;
  }
  
  .page-btn:hover:not(:disabled) {
    border-color: #1E9FFF;
    color: #1E9FFF;
  }
  
  .page-btn:disabled {
    cursor: not-allowed;
    opacity: 0.5;
  }
  
  .page-numbers {
    display: flex;
    gap: 5px;
  }
  
  .page-number {
    padding: 5px 10px;
    cursor: pointer;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
  }
  
  .page-number:hover {
    border-color: #1E9FFF;
    color: #1E9FFF;
  }
  
  .page-number.active {
    background: #1E9FFF;
    color: #fff;
    border-color: #1E9FFF;
  }
  
  .page-number:contains('...') {
    cursor: default;
    border: none;
  }
  
  .page-jumper {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 14px;
  }
  
  .page-input {
    width: 60px;
    padding: 3px 5px;
    border: 1px solid #ddd;
    border-radius: 4px;
    text-align: center;
  }

.class-table,
.student-table {
  width: 100%;
  border-collapse: collapse;
}

.class-table th,
.student-table th {
  background-color: #f5f5f5;
  padding: 12px;
  text-align: left;
  font-weight: 500;
  color: #666;
  border-bottom: 2px solid #e8e8e8;
}

.class-table td,
.student-table td {
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.empty-tip {
  text-align: center;
  padding: 60px;
  color: #999;
}

.loading-indicator {
  text-align: center;
  padding: 60px;
  color: #666;
  font-size: 16px;
  background-color: #f5f5f5;
  border-radius: 4px;
  margin-bottom: 20px;
}

/* 弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 500px;
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-content.large {
  width: 800px;
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #666;
  font-weight: 500;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.modal-footer {
  padding: 20px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.submit-btn {
  background-color: #1E9FFF;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn:hover {
  background-color: #40A9FF;
}

.cancel-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background-color: white;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn:hover {
  background-color: #f5f5f5;
}
</style>